import ai_cloud as ai
from wxauto import WeChat
import time
import re
from my_instruction import *

wx = WeChat()
file_path = 'names.txt'
listen_list = []

to_reply_dict={} # {聊天窗口名：([消息数组],时间戳)}

# 读取好友列表
with open(file_path, 'r', encoding='utf-8') as file:
    try:
        for line in file:
            line = line.strip()  # 去掉首尾的空白字符和换行符
            if not line:
                continue  # 跳过空行
            parts = line.split(maxsplit=1)  # 按第一个空格分割，最多分割一次
            if len(parts) == 0:
                continue
            name = parts[0]  # 第一个部分是名称
            introduce = parts[1] if len(parts) > 1 else None  # 简介部分，若没有则为 None
            
            to_reply_dict[name] = [[],time.time()]
            
            wx.AddListenChat(who=name, savepic=True)  # 添加好友到监听列表
            print(f"添加好友 {name} 到监听列表")

            ai.add_user(name, introduce)
            
            # ai.add_history(name,"user","可以使用的表情包：[微笑], [撇嘴], [色], [发呆], [得意], [流泪], [害羞], [闭嘴], [睡], [大哭], [尴尬], [发怒], [调皮], [呲牙], [惊讶], [难过], [囧], [抓狂], [吐], [偷笑], [愉快], [白眼], [傲慢], [困], [惊恐], [憨笑], [悠闲], [咒骂], [疑问], [嘘], [晕], [衰], [骷髅], [猪头], [敲打], [再见], [擦汗], [抠鼻], [鼓掌], [坏笑], [右哼哼], [鄙视], [委屈], [快哭了], [阴险], [亲亲], [可怜], [笑脸], [生病], [脸红], [破涕为笑], [恐惧], [失望], [无语], [嘿哈], [捂脸], [奸笑], [机智], [皱眉], [耶], [吃瓜], [加油], [汗], [天啊], [Emm], [社会社会], [旺柴], [好的], [打脸], [哇], [翻白眼], [666], [让我看看], [叹气], [苦涩], [裂开], [嘴唇], [爱心], [心碎], [拥抱], [强], [弱], [握手], [胜利], [抱拳], [勾引], [拳头], [OK], [合十], [啤酒], [咖啡], [蛋糕], [玫瑰], [凋谢], [菜刀], [便便], [月亮], [太阳], [礼物], [红包], [發], [福], [跳跳], [发抖], [转圈], [炸弹], [庆祝], [烟花]。请注意一次回答最多只能使用一次表情包，禁止使用[微笑]")
            # ai.add_history(name,"assistant","收到")
            # ai.add_history(name,"user","禁用表情包,别发表情了，不允许发表情")
            # ai.add_history(name,"assistant","收到")
            
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到，请检查路径！")
    except Exception as e:
        print(f"读取文件时发生错误：{e}")




wait = 1  # 设置间隔时间
while True:
    flag_sleep=True
    msgs = wx.GetListenMessage()
    print("获取消息")
    for chat in msgs:
        windows_who = chat.who  # 获取聊天窗口名（人或群名）
        one_msgs = msgs[chat] # 获取消息内容
        prompts=[]
        len0=0
        print("-"*50)
        print(f'窗口-{windows_who}')
        for msg in one_msgs:
            msgtype = msg.type  # 获取消息类型
            content = msg.content  # 获取消息内容
            sender=msg.sender # 获取发送者
            print(f'【{sender}】：{content}')

            if msgtype == 'friend':
                if content.startswith("指令"):
                    # ins_sendMsgTo(chat)
                    str_list=re.split(r"[\s]+",content.strip())
                    if len(str_list)>=2: # 防止空指令
                        match str_list[1]:
                            case "获取群聊成员":
                                if len(str_list)>=3:
                                    print(str_list[2])
                                    member_list=ins_getGroupMembers(wx,str_list[2])
                                    chat.SendMsg(member_list)
                            case "加好友":
                                if len(str_list)>=4:
                                    # print(f"{str_list[2]},{str_list[3]}")
                                    ins_addFriend(wx=wx,keywords=str_list[2],remark=str_list[3])
                            case "接受好友申请":
                                info=ins_acceptFriend(wx)
                                if info:
                                    (friend_name,friend_info)=info
                                    reply=f"已添加好友：【{friend_name}】\n对方申请信息：{friend_info}"
                                    chat.SendMsg(reply)
                                    print("-"*50)
                                    print(reply)
                                else:
                                    chat.SendMsg('暂无好友申请')
                            case "语音通话":
                                if len(str_list)>=3:
                                    ins_voiceCall(wx=wx,name=str_list[2])
                            case _:
                                ins_sendMsgTo(chat)
                else:
                    prompts.append(sender+":"+content)
        
        # len0=len(to_reply_dict[windows_who][0])
        if len(prompts) > 0:
            to_reply_dict[windows_who][1]=time.time()
            # print("to_reply:%s \n -----" % to_reply_dict[windows_who][0])
        for i in prompts:
            to_reply_dict[windows_who][0].append(i)

    for to_reply in to_reply_dict:
        msg_list=to_reply_dict[to_reply][0]
        time0=to_reply_dict[to_reply][1]
        time1 = time.time()
        if len(msg_list)>0 and time1-time0 > 6.0:
            wx.SendMsg(msg=ai.chat(to_reply, msg_list),who=to_reply)
            print("time1-time0:%f" % (time1-time0))
            to_reply_dict[to_reply][0]=[]
            flag_sleep=False
    if flag_sleep: # 此次没发送则休眠一下
        time.sleep(7)
